package com.util_code.room;

import android.content.Context;

import androidx.annotation.NonNull;

import com.util_code.utils.ThreadUtils;

import java.util.List;

import io.reactivex.Flowable;

public class NetLogInfoDataSource {

    private static volatile NetLogInfoDataSource INSTANCE;

    private NetLogInfoDao mNetLogInfoDao;

    NetLogInfoDataSource(NetLogInfoDao NetLogInfoDao) {
        mNetLogInfoDao = NetLogInfoDao;
    }

    public static NetLogInfoDataSource getInstance(@NonNull Context context) {
        if (INSTANCE == null) {
            synchronized (NetLogInfoDataSource.class) {
                if (INSTANCE == null) {
                    RoomDataBase database = RoomDataBase.getInstance(context);
                    INSTANCE = new NetLogInfoDataSource(database.netLogInfoDao());
                }
            }
        }
        return INSTANCE;
    }

    public Flowable<List<NetLogInfo>> getNetLogInfo() {
        return mNetLogInfoDao.loadAll();
    }

    public Flowable<List<NetLogInfo>> getNetLogInfoByDate(String datetime) {
        return mNetLogInfoDao.loadNetLogInfoByDate(datetime);
    }

    public List<NetLogInfo> synLoadNetLogInfoByDate(String datetime) {
        return mNetLogInfoDao.synLoadNetLogInfoByDate(datetime);
    }

    public void insertOrUpdateNetLogInfo(NetLogInfo NetLogInfo) {
        mNetLogInfoDao.insertNetLogInfo(NetLogInfo);
    }

    public void deleteNetLogInfo(NetLogInfo NetLogInfo) {
        mNetLogInfoDao.delete(NetLogInfo);
    }

    public void deleteAllNetLogInfo() {
        // android room Cannot access database on the main thread since it may
        // potentially lock the UI for a long period of time.
        ThreadUtils.newSingleThreadExecutor(NetLogInfo.class.getSimpleName())
                .execute(new Runnable() {
                    @Override
                    public void run() {
                        mNetLogInfoDao.deleteAllNetLogInfo();
                    }
                });
    }
}